<?php
/**
 * 商品逻辑层
 * @author maniac
 */
namespace app\common\logic;

use app\common\model\Point AS PointModel;
use app\common\model\PointSku;
use app\common\model\GoodAttrs;
use app\common\model\GoodAttrValue;
use app\facade\Options AS OptionsFacade;

class Point extends Base
{
    /**
     * 重组提交信息
     * @param  array $data 请求的信息
     */
    public function recombine($data)
    {
        $data['store_id'] = isset($data['store_id']) && $data['store_id'] ? (int)$data['store_id'] : 0;
        if (isset($data['goods_sn']) && $data['goods_sn']) {
            $option        = unserialize(OptionsFacade::option('shop_info'));
            $goodsSnPrefix = isset($option['goods_sn_prefix']) && $option['goods_sn_prefix'] ? $option['goods_sn_prefix'] : '';
            $data['goods_sn'] = $goodsSnPrefix.$option['goods_sn_prefix'];
        }
        $this->validateData($data);
        $goods_album = [];
        if (isset($data['goods_album']) && !empty($data['goods_album'])) {
            foreach ($data['goods_album']['desc'] as $key => $val) {
                $goods_album[$key] = [
                    'value' => $data['goods_album']['value'][$key],
                    'desc'  => $val,
                ];
            }
        }
        
        $data['give_points']      = isset($data['give_points']) ? (float)$data['give_points'] : 0;
        $data['goods_album']      = serialize($goods_album);
        $data['goods_thumb_id']   = isset($data['goods_thumb_id']) ? (int)$data['goods_thumb_id'] : 0;
        $data['is_sale']          = isset($data['is_sale']) && $data['is_sale'] ? (int)$data['is_sale'] : 0;
        $data['is_latest']        = isset($data['is_latest']) && $data['is_latest'] ? (int)$data['is_latest'] : 0;
        $data['is_hot_sale']      = isset($data['is_hot_sale']) && $data['is_hot_sale'] ? (int)$data['is_hot_sale'] : 0;
        $data['is_recommand']     = isset($data['is_recommand']) && $data['is_recommand'] ? (int)$data['is_recommand'] : 0;
        $data['is_stock_visible'] = isset($data['is_stock_visible']) && $data['is_stock_visible'] ? (int)$data['is_stock_visible'] : 0;
        $data['goods_stock']      = $this->calcStock($data);
        unset($data['actual_sale_nums']);
        if (isset($data['goods_video']['name'])) {
            foreach ($data['goods_video']['name'] as $key => $val) {
                $arr[$key] = [
                    'value' => $data['goods_video']['value'][$key],
                    'name'  => $val,
                ];
            }
            $data['goods_video'] = serialize($arr);
        } else {
            $data['goods_video'] = '';
        }
        if (!isset($data['goods_detail']) || !trim($data['goods_detail'])) {
            exception('请输入商品详情');
        }
        /*检测是什么级别的人添加的商品*/
        if (isset($data['id']) && $data['id']) {
            // 编辑
        }
        else{
            //添加
            $userid = session('userid', '', session_prefix());
            if($userid == 1)
            {
                $data['status'] = 1;//超级管理员  通过审核
            }
            else{
                $data['status'] = 0;//普通供应商 未通过审核
            }
        }
        return $data;
    }
    
    /**
     * 添加/编辑逻辑处理
     * @param  array $data 请求的信息
     */
    public function save($data)
    {
        if (isset($data['id']) && $data['id']) {
            // 编辑
            $info = PointModel::field('is_sale')->where('id', $data['id'])->find();
            // 上下架状态被改变，修改上下架时间
            if ($data['is_sale'] != $info['is_sale']) {
                $data['sale_time'] = time();
            }
        } else {
            $data['sale_time'] = time();
        }
        $sku = [];
        if (isset($data['sku'])) {
            $sku = $data['sku'];
            unset($data['sku']);
        }
        $attr = [];
        if (isset($data['attr'])) {
            $attr = $data['attr'];
            unset($data['attr']);
        }
        $result = parent::save($data);
        if ($result) {
            $data['id'] = isset($data['id']) && $data['id'] ? $data['id'] : $result;
            if ($sku) {
                $this->updateSku($data['store_id'], $data['id'],2, $sku);
            }
            if ($attr) {
                $this->updateAttr($data['store_id'], $data['id'], $attr);
            }
        }
        return $result;
    }
    
    /**
     * 修改状态附件
     * @param  array $data 请求的信息
     */
    public function statusAttach($data)
    {
        $update = [
            'id'         => $data['id'],
            $data['key'] => $data['value'] ? 0 : 1,
        ];
        if ($data['key'] == 'is_sale') {
            $update['sale_time'] = time();
        }
        return $update;
    }
    
    private function validateData($data)
    {
        if (!isset($data['goods_name']) || trim($data['goods_name']) == '') {
            exception('请输入商品名称');
        }
        if (isset($data['goods_sn']) && $data['goods_sn'] && !isset($data['sku'])) {
            $option = 
            $where = [
                'store_id' => $data['store_id'],
                'goods_sn' => $data['goods_sn'],
            ];
            $info = PointModel::where($where)->find();
            if ($info) {
                exception('商品货号已存在');
            }
        }
//         if (!isset($data['category_id']) || !$data['category_id']) {
//             exception('请选择商品分类');
//         }
        if (isset($data['sku'])) {
            foreach ($data['sku']['point'] as $v) {
                if ($v == false) {
                    exception('请完善商品 sku 属性的积分数量');
                }
            }
        } /*elseif ((float)$data['sale_price'] == false) {
            exception('请输入商品销售价');
        }*/
    }
    
    /**
     * 计算商品库存
     * @param  array $data 请求的信息
     */
    private function calcStock($data)
    {
        if (!isset($data['sku']) || empty($data['sku']['stock'])) {
            if (!(int)$data['goods_stock']) {
                exception('请输入商品库存');
            }
            return (int)$data['goods_stock'];
        }
        $count = 0;
        foreach ($data['sku']['stock'] as $v) {
            $count += (int)$v;
        }
        if ($count == 0) {
            exception('请输入商品库存');
        }
        return $count;
    }
    
    /**
     * 编辑商品 sku 信息
     * @param  int   $store_id 店铺 id
     * @param  int   $goods_id 商品 id
     * @param  array $data     商品 sku 信息
     */
    private function updateSku($store_id, $goods_id,$type, $data)
    {
        if ($goods_id && isset($data['sku_id']) && !empty($data['sku_id'])) {
            // 商品原始 sku
            $originSku = PointSku::where(['store_id' => $store_id, 'goods_id' => $goods_id])->order('id ASC')->column('id');
            $deleteSku = array_values(array_diff($originSku, $data['id']));
            if (!empty($deleteSku)) {
            // 删除去除的 sku
                PointSku::destroy($deleteSku);
            }
            
            // 获取商品 skuid 最后一个索引
            $index = count($data['sku_id']) - 1;
            $key   = 0;
            foreach ($data['sku_id'][$index] as $k => $v) {
                $update[$key] = [
                    //'sku_sn'       => $data['sku_sn'][$k],
                    'sku_name'     => $data['sku_name'][$index][$k],
                    //'cost_price'   => (float)$data['cost_price'][$k],
                    'market_price' => (float)$data['market_price'][$k],
                    'point'   => (int)$data['point'][$k],
                    'stock'        => (int)$data['stock'][$k],
                ];
                if (isset($data['id'][$k]) && $data['id'][$k]) {
                    // 存在主键 id，需要更新，传入更新条件
                    $update[$key]['id'] = $data['id'][$k];
                } else {
                    // 不存在主键 id，新增
                    $update[$key]['store_id'] = $store_id;
                    $update[$key]['goods_id'] = $goods_id;
                    $update[$key]['type'] = $type;
                    $update[$key]['sku_id']   = $v;
                }
                $key++;
            }
            // 批量更新，根据是否存在更新条件来自动执行更新或添加
            (new PointSku)->saveAll($update);
        }
    }
    
    /**
     * 编辑商品属性信息
     * @param  int   $store_id 店铺 id
     * @param  int   $goods_id 商品 id
     * @param  array $data     商品属性信息
     */
    private function updateAttr($store_id, $goods_id, $data)
    {
        if ($goods_id && !empty($data)) {
            // 获取数组所有索引，得到所有属性 id 值
            $keys  = array_keys($data);
            $where = [
                ['id', 'in', $keys],
            ];
            // 以 id 为索引，获取所有属性名称
            $attrs  = GoodAttrs::where($where)->column('name', 'id');
            $update = [];
            $index  = 0;
            $ids    = [];
            foreach ($data as $key => $val) {
                $update[$index] = [
                    'store_id'   => $store_id,
                    'goods_id'   => $goods_id,
                    'attr_id'    => $key,
                    'attr_name'  => $attrs[$key],
                    'attr_value' => isset($val['value']) && $val['value'] ? implode(',', $val['value']) : '',
                ];
                if (isset($val['id']) && $val['id']) {
                    $ids[] = $val['id'];
                    // 存在主键 id，需要更新，传入更新条件
                    $update[$index]['id'] = $val['id'];
                }
                $index++;
            }
            // 商品原始属性
            $originAttr = GoodAttrValue::where(['store_id' => $store_id, 'goods_id' => $goods_id])->order('id ASC')->column('id');
            $deleteAttr = array_values(array_diff($originAttr, $ids));
            if (!empty($deleteAttr)) {
                // 删除去除的 sku
                GoodAttrValue::destroy($deleteAttr);
            }
            // 批量更新，根据是否存在更新条件来自动执行更新或添加
            (new GoodAttrValue)->saveAll($update);
        }
    }
}
